const router = require('koa-router')()
const { formatDate } = require('../utils/tools')
const { getList, addItem, deleteItem, updateItem, getSingle ,checkUserName } = require('../service/demo')
const path = require('path')
const fse = require('fs-extra')
const fs = require('fs')
const { SuccessModel, ErrorModel } = require('../model/ResModel')
//const urlPrefix = 'http://localhost:3003'
//const qetag = require('node-qetag')


// 存储目录
const DIST_FOLDER_PATH = path.join(__dirname, '..', '..', '..', 'uploadFiles')

// 是否需要创建目录
fse.pathExists(DIST_FOLDER_PATH).then(exist => {
    if (!exist) {
        fse.ensureDirSync(DIST_FOLDER_PATH)
    }
})

//可以设置一个枚举变量

const tableNames = ['users', 'articles', 'products', 'movies', 'comments', 'categories', 'courses', 'subitems']

router.prefix('/api/demo/')


router.post('/additem', async (ctx, next) => {
    const data = ctx.request.body
    let tableName = getTableName(data.typeIndex)
    const r = await addItem(data, tableName)
    ctx.body = { id: r.insertId }
})


router.post('/updateitem', async (ctx, next) => {

    const data = ctx.request.body
    let tableName = getTableName(data.typeIndex)
    const r = await updateItem(data, false, tableName)

    ctx.body = 'ok'

})

router.post('/deleteitem', async (ctx, next) => {

    const { delid, typeIndex } = ctx.request.body //只能删除自己添加的！！
    let tableName = getTableName(typeIndex)
    ctx.body = await deleteItem(delid, tableName)

})



router.get('/getallitems', async (ctx, next) => {
    const data = ctx.request.query
    let tableName = getTableName(data.typeIndex)

    const result = await getList(tableName,data)     // 
    for (let i = 0; i < result.length; i++) {
        const item = result[i]
        item.addedTime = formatDate(item.addedTime, true)
        item.authorName = '匿名用户'
        if (item.userid) {
            const uinfo = await getSingle({ id: item.userid }, 'users')
            if (uinfo)
                item.authorName = uinfo.username
        }
    }
    ctx.body = result
})

router.get('/getsingle', async (ctx, next) => {
    const data = ctx.request.query
    let tableName = getTableName(data.typeIndex)
    const result = await getSingle(data, tableName)     // 
    if (result) {
        result.addedTime = formatDate(result.addedTime, true)
        result.authorName = '匿名用户'
        if (result.userid) {
            const uinfo = await getSingle({ id: result.userid }, 'users')
            if (uinfo)
                result.authorName = uinfo.username

        }
    }

    ctx.body = result
})
router.post('/reg', async (ctx, next) => {

    const data = ctx.request.body
    try {
        const r = await checkUserName(data.username)
        console.log("r",r)
        if(r)
            ctx.body = new ErrorModel({errno:10001,message:'用户名已存在'})
        else ctx.body= await addItem(data, 'users', true)
    } catch (error) {
        console.error(error)
        ctx.body ='error!!!'
    }
    console.log(ctx.body)
})
router.post('/login', async (ctx, next) => {

    const data = ctx.request.body
    console.log(data)
    try {
        const r = await getSingle(data, 'users', true)
        if (r) {
            ctx.body = { errno: 0, data: r }

        } else {
            ctx.body = { errno: 1, message: 'not such user!!' }    //"no such user!!"
        }

    } catch (error) {
        console.error(error)

        ctx.body = 'error!!'
    }
})

//上传图片
router.post('/image', async (ctx, next) => {
    const files = ctx.request.files
    const file = files['wangeditor-uploaded-image'] // 获取上传文件 

    ctx.body = await saveFileByStream(file, 'images/demo')
})

//上传视频
router.post('/video', async (ctx, next) => {
    const files = ctx.request.files
    const file = files['wangeditor-uploaded-video'] // 获取上传文件 

    ctx.body = await saveFileByStream(file, 'videos/demo')
})
function getTableName(typeIndex) {
    let tableName = 'articles'
    if (typeIndex && typeIndex > 0 && typeIndex < tableNames.length) {
        tableName = tableNames[typeIndex]
    }
    return tableName
}
async function saveFileByStream(file, subpath) {
    await fse.ensureDir(DIST_FOLDER_PATH + '/' + subpath)

    const reader = fs.createReadStream(file.path)

    const extName = path.extname(file.name)// 获取上传文件扩展名
    const fileName = Date.now() + extName // 防止重名
    const distFilePath = path.join(DIST_FOLDER_PATH, subpath, fileName) // 目的地
    // 创建可写流
    const upStream = fs.createWriteStream(distFilePath)
    // 可读流通过管道写入可写流
    reader.pipe(upStream)
    // 返回信息
    return new SuccessModel({

        url: `/${subpath}/${fileName}`  //${urlPrefix}
    })

}
module.exports = router


